﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.IncomingMaterialsManage;
using ProduceBasicData.Domain.IncomingMaterialsManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.IncomingMaterialsManage
{
    /// <summary>
    /// 删除来料检验命令处理器
    /// </summary>
    public class DeleteIncomingInspectionHandler : IRequestHandler<DeleteIncomingInspectionCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<IncomingInspection> _incomingInspectionRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="incomingInspectionRepository">来料检验仓储接口</param>
        /// <param name="mapper">对象映射器</param>
        public DeleteIncomingInspectionHandler(IBaseRespository<IncomingInspection> incomingInspectionRepository, IMapper mapper)
        {
            _incomingInspectionRepository = incomingInspectionRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理删除来料检验命令
        /// </summary>
        /// <param name="request">删除来料检验命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含操作结果的ApiResult</returns>
        public async Task<ApiResult<int>> Handle(DeleteIncomingInspectionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID获取来料检验数据
                var incomingInspection = await _incomingInspectionRepository.GetModelAsync(request.Id);
                if (incomingInspection == null)
                {
                    // 来料检验不存在时返回错误信息
                    return new ApiResult<int>
                    {
                        Msg = "来料检验不存在",
                        Code = ApiEnum.Failed
                    };
                }

                // 执行软删除（标记Isdel为true）
                incomingInspection.Isdel = true;
                await _incomingInspectionRepository.Update(incomingInspection);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "删除成功",
                    Data = incomingInspection.Id
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除来料检验时发生错误: {ex.Message}"
                };
            }
        }
    }
}
